package com.cgly.medical.security;

import com.cgly.medical.entity.AccountModel;
import com.cgly.medical.util.Msg;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: CGLY
 * @description:* 访问决策管理器
 *  * 只要任一 AccessDecisionVoter 返回肯定的结果，便授予访问权限。
 * @author: chen di
 * @create: 2022-08-28 23:04
 */
@Component
public class CustomUrlDecisionManager  implements AccessDecisionManager {

    /**
     *
     * @param authentication 当前用户的角色信息
     * @param object
     * @param configAttributes  CustomFilterInvocationSecurityMetadataSource 的 getAttributes 方法传过来的：当前请求需要的角色
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        for (ConfigAttribute configAttribute : configAttributes) {
            String needRole = configAttribute.getAttribute();
            if(needRole .equals("ROLE_0"))
                return;

            AccountModel principal = (AccountModel) authentication.getPrincipal();//获取当前用户的权限

            String curRole = principal.getUtype();
            if (curRole.equals(needRole)) {
                return;
            }
        }
        throw new AccessDeniedException("权限不足，请联系管理员!");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }


    public void handle1(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(Msg.fail().mess("无访问权限").code(10007)));
    }
}